package io.sundial.console.authentication;

import io.regent.commons.jwt.JWT;
import io.regent.commons.jwt.JWTException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证API
 *
 * @author Payne 646742615@qq.com
 * 2019/1/3 13:05
 * @tag 认证
 */
@CrossOrigin
@RestController
@RequestMapping("/api/authentication")
public class AuthenticationController {

    @Value("${jwt.expiresIn}")
    private long expiresIn;

    @Value("${jwt.secretKey}")
    private String secretKey;

    /**
     * 认证接口
     * 通过用户名密码获取Access-Token
     *
     * @param param 认证参数
     * @return 认证结果
     * @throws JWTException Json Web Token 异常
     */
    @PostMapping
    @ResponseBody
    public AuthenticateResult authenticate(@RequestBody @Valid AuthenticateParam param) throws JWTException {
        final AuthenticateResult result = new AuthenticateResult();

        if (!"admin".equalsIgnoreCase(param.getUsername()) || !"admin".equalsIgnoreCase(param.getPassword())) {
            return result.error(401, "用户名或密码错误");
        }

        final String token = JWT.builder()
                .setSubject(param.getUsername())
                .setIssuedAt(System.currentTimeMillis())
                .setExpires(expiresIn)
                .build()
                .encode(secretKey);

        result.setExpiresIn(expiresIn);
        result.setToken(token);

        return result;
    }

}
